package com.example.administrator.yanfoxconn.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.example.administrator.yanfoxconn.R;
import com.example.administrator.yanfoxconn.adapter.KHBodyListAdapter;
import com.example.administrator.yanfoxconn.adapter.KHHeadListAdapter;
import com.example.administrator.yanfoxconn.bean.KHInfo;
import com.example.administrator.yanfoxconn.constant.Constants;
import com.example.administrator.yanfoxconn.constant.FoxContext;
import com.example.administrator.yanfoxconn.utils.BaseActivity;
import com.example.administrator.yanfoxconn.utils.HttpUtils;
import com.example.administrator.yanfoxconn.utils.TimeDateUtils;
import com.example.administrator.yanfoxconn.utils.ToastUtils;
import com.example.administrator.yanfoxconn.widget.MyListView;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.RequiresApi;
import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 用途：人資-訪談記錄 人員列表界面
 * Created by Song on 2021/9/14.
 */
public class KHPeopleListActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
    @BindView(R.id.tv_title)
    TextView tvTitle;//標題
    @BindView(R.id.btn_title_left)
    Button btnBack;//返回

    @BindView(R.id.tv_type)
    TextView tvType;//訪談類型
    @BindView(R.id.tv_date)
    TextView tvDate;//訪談日期
    @BindView(R.id.tv_position)
    TextView tvPosition;//訪談地址
    @BindView(R.id.mlv)
    MyListView mLv;

    private KHBodyListAdapter khBodyListAdapter;
    private List<KHInfo> peopleList;
    private String iId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kh_people_list);
        ButterKnife.bind(this);
        btnBack.setOnClickListener(this);
        mLv.setOnItemClickListener(this);
        tvTitle.setText("訪談明細瀏覽");
        tvType.setText(getIntent().getStringExtra("type"));
        tvDate.setText(getIntent().getStringExtra("date"));
        tvPosition.setText(getIntent().getStringExtra("position"));
        iId=getIntent().getStringExtra("id");
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_title_left://返回
                finish();
                break;
        }
    }

    //提交信息
    private void getMsessage(String iId) {

        final String url = Constants.HTTP_BODY_LIST+"?i_id="+iId; //此處寫上自己的URL

        //開啟一個新執行緒，向伺服器上傳資料
        new Thread() {
            public void run() {
                //把网络访问的代码放在这里
                try {
                    showDialog();
                    String result = HttpUtils.queryStringForPost(url);

                    Gson gson = new Gson();
                    if (result != null) {
                        dismissDialog();
                        Log.e("----result-----",  result);
                        JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                        String errCode = jsonObject.get("errCode").getAsString();
                        if (errCode.equals("200")) {

                            JsonArray array = jsonObject.get("data").getAsJsonArray();
                            if (!array.equals(null)){
                                peopleList = new ArrayList<KHInfo>();

                                for (JsonElement type : array) {
                                    KHInfo humi = gson.fromJson(type, KHInfo.class);
                                    peopleList.add(humi);
                                }
                                Message message = new Message();
                                message.what = Constants.MESSAGE_SET_TEXT;
                                message.obj = "此条件无数据！";
                                mHandler.sendMessage(message);

                            } else {
                                Message message = new Message();
                                message.what = Constants.MESSAGE_TOAST;
                                message.obj = jsonObject.get("errMessage").getAsString();
                                mHandler.sendMessage(message);
                            }}
                    }else{
                        Message message = new Message();
                        message.what = Constants.MESSAGE_NETMISTAKE;
                        mHandler.sendMessage(message);
                        finish();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    Handler mHandler = new Handler() {
        @RequiresApi(api = Build.VERSION_CODES.M)
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case Constants.MESSAGE_TOAST://Toast彈出
                    ToastUtils.showLong(KHPeopleListActivity.this, msg.obj.toString());
//                    finish();
                    break;
                case Constants.MESSAGE_SET_TEXT://text賦值
                    khBodyListAdapter = new KHBodyListAdapter(KHPeopleListActivity.this,peopleList);
                    mLv.setAdapter(khBodyListAdapter);
                    setListViewHeightBasedOnChildren(mLv);

//                    aboutAlert(msg.obj.toString(),MESSAGE_SET_TEXT);
                    break;
                case Constants.MESSAGE_DONE://提交響應
//                    check();
                    break;

            }
            super.handleMessage(msg);
        }
    };
    /**
     * 用於解決scrollview嵌套listview導致只顯示一條數據的問題
     *
     * @param listView
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        KHBodyListAdapter listAdapter = (KHBodyListAdapter) listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() *
                (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(KHPeopleListActivity.this,KHPeopleAddAndDetailActivity.class);
        intent.putExtra("info", (Serializable) peopleList.get(position));
        intent.putExtra("id","");
        intent.putExtra("workFlag", getIntent().getStringExtra("type"));
        startActivity(intent);
    }

    @Override
    protected void onStart() {
        getMsessage(iId);
        super.onStart();
    }
}
